import 'package:family_expense/features/bank_card/models/bank_card.dart';
import 'package:family_expense/features/bank_card/services/bank_card_service.dart';
import 'package:family_expense/features/bank_card/widgets/bank_card_home.dart';
import 'package:family_expense/features/bank_card/widgets/bank_card_shared.dart';
import 'package:family_expense/features/bank_card/widgets/bank_shared.dart';
import 'package:family_expense/features/credit_card_bill/widgets/credit_card_bill_view.dart';
import 'package:family_expense/features/income_expense/constants/payment_type.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter_core/my_flutter_core.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';

class CreditCardBillHome extends StatefulWidget {
  const CreditCardBillHome({super.key});

  // For retrieving bank logo.
  @override
  State<CreditCardBillHome> createState() => _CreditCardBillHomeState();
}

class _CreditCardBillHomeState extends State<CreditCardBillHome> {
  final BankCardService _bankCardService = BankCardService();
  final DateTime _currentDate = getCurrentDateTime();

  BankCard? _selectedBankCard;
  User? _currentUser;

  late int _selectedYear = _currentDate.year;
  late int _selectedMonth = _currentDate.month;
  late List<BankCard> _creditCards;

  @override
  void initState() {
    super.initState();

    _loadCurrentUser();
    _getCreditCards();
  }

  @override
  Widget build(BuildContext context) {
    return _creditCards.isNotEmpty
        ? _bulidMenuList()
        : _buildOpenBankCardSettingViewMenu();
  }

  /// Builds the menu list for bank card, bill month related selection.
  Widget _bulidMenuList() {
    return ListView(
      padding: const EdgeInsets.all(10.0),
      children: [
        SimpleDetailListTile(
          title: const Text('选择卡片'),
          value: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              BankLogo(_selectedBankCard!.bank!),
              const SizedBox(width: 10.0),
              Text(_selectedBankCard!.name!),
            ],
          ),
          onTap: () {
            BankCardShared.showBankCardModalBottomSheet(
              context,
              _creditCards,
              (bankCard) {
                if (mounted) {
                  setState(() => _selectedBankCard = bankCard);
                }

                // Pops the modal.
                NavigatorHelper.pop(context);
              },
              title: '选择卡片',
              bankCard: _selectedBankCard,
            );
          },
        ),
        SimpleDetailListTile(
          title: const Text('选择年份'),
          value: Row(
            mainAxisSize: MainAxisSize.min,
            children: [const SizedBox(width: 10.0), Text('$_selectedYear')],
          ),
          onTap: () {
            _showYearModalBottomSheet((year) {
              if (mounted) {
                setState(() => _selectedYear = year);
              }

              // Pops the modal.
              NavigatorHelper.pop(context);
            }, year: _selectedYear);
          },
        ),
        SimpleDetailListTile(
          title: const Text('选择月份'),
          value: Row(
            mainAxisSize: MainAxisSize.min,
            children: [const SizedBox(width: 10.0), Text('$_selectedMonth')],
          ),
          onTap: () {
            _showMonthModalBottomSheet((month) {
              if (mounted) {
                setState(() => _selectedMonth = month);
              }

              // Pops the modal.
              NavigatorHelper.pop(context);
            }, month: _selectedMonth);
          },
        ),
        TextButton(
          style: TextButton.styleFrom(
            textStyle: const TextStyle(fontSize: 16.0),
          ),
          onPressed: () => NavigatorHelper.push(
            context,
            CreditCardBillView(
              _selectedBankCard!,
              _selectedYear,
              _selectedMonth,
            ),
          ),
          child: const Text('查看账单'),
        ),
      ],
    );
  }

  /// Builds the menu for open bank card setting view.
  /// Only account group admin can go to setting view.
  Widget _buildOpenBankCardSettingViewMenu() {
    return InkWell(
      onTap: _currentUser?.isAccountGroupAdmin == true
          ? () async {
              final dataUpdated = await NavigatorHelper.push<bool>(
                context,
                const BankCardHome(),
              );

              if (dataUpdated == true && mounted) {
                setState(() => _getCreditCards());
              }
            }
          : null,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.credit_card, size: 100.0, color: Colors.grey),
            Text(
              '目前还没有信用卡${_currentUser?.isAccountGroupAdmin == true ? "，点击屏幕去设置。" : ""}',
              style: const TextStyle(fontSize: 14.0, color: Colors.grey),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _loadCurrentUser() async {
    // Loads current user from local storage.
    final res = await AuthStateService.instance.currentUser;

    if (mounted) {
      setState(() => _currentUser = res);
    }
  }

  /// Shows a pick modal for year selection.
  void _showYearModalBottomSheet(ValueChanged<int> onTap, {int? year}) {
    // The year selection range begins with 2019, the year this app released.
    const initalYear = 2018;

    // The current year will be the end of the year selection range.
    final currentYear = _currentDate.year;

    final totalYear = currentYear - initalYear + 1;

    showModalBottomSheet<void>(
      context: context,
      builder: (context) => Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const SizedBox(height: 20.0),
          Text('年份', style: Theme.of(context).textTheme.titleLarge),
          const SizedBox(height: 20.0),
          SizedBox(
            height: 180.0,
            child: ScrollablePositionedList.builder(
              itemCount: totalYear,
              initialScrollIndex: totalYear > 3 ? currentYear - year! : 0,
              itemBuilder: (context, index) {
                final i = currentYear - index;

                return ListTile(
                  selected: i == year,
                  title: Text('$i'),
                  onTap: () => onTap(i),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  /// Shows a pick modal for month selection.
  void _showMonthModalBottomSheet(ValueChanged<int> onTap, {int? month}) {
    const totalMonth = 12;

    showModalBottomSheet<void>(
      context: context,
      builder: (context) => Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const SizedBox(height: 20.0),
          Text('月份', style: Theme.of(context).textTheme.titleLarge),
          const SizedBox(height: 20.0),
          SizedBox(
            height: 230.0,
            child: ScrollablePositionedList.builder(
              itemCount: totalMonth,
              initialScrollIndex: totalMonth - month!,
              itemBuilder: (context, index) {
                final i = totalMonth - index;

                return ListTile(
                  selected: i == month,
                  title: Text('$i'),
                  onTap: () => onTap(i),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  /// Gets the credit cards from all bank cards.
  void _getCreditCards() {
    // Gets all bank cards from cache.
    final bankCards = _bankCardService.currentBankCards;

    // Gets all credit cards.
    _creditCards = bankCards?.isNotEmpty == true
        ? BankCardShared.getRelatedBankCards(bankCards!, PaymentType.creditCard)
        : [];

    // Sets the default selected card.
    _selectedBankCard = _creditCards.isNotEmpty ? _creditCards.first : null;
  }
}
